package com.enjoy.controller;

import com.enjoy.common.Result;
import com.enjoy.common.constant.Constants;
import com.enjoy.domain.dto.LoginDTO;
import com.enjoy.domain.VdsUser;
import com.enjoy.service.LoginService;
import com.enjoy.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 姜风
 * @date 2021/9/7 9:56
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody LoginDTO loginDTO) {
        if (StringUtils.isEmpty(loginDTO.getUsername()) || StringUtils.isEmpty(loginDTO.getPassword())) {
            return Result.error("请输入用户名和密码！");
        }
        // 用户认证信息
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginDTO.getUsername(), loginDTO.getPassword(),false);

        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            log.error("用户名不存在！", e);
            return Result.error("用户名不存在！");
        } catch (AuthenticationException e) {
            log.error("密码错误！", e);
            return Result.error("密码错误！");
        } catch (AuthorizationException e) {
            log.error("没有权限！", e);
            return Result.error("没有权限");
        }
        VdsUser user = loginService.getUserByName(loginDTO.getUsername());
        session.setAttribute(Constants.SESSION_USER,user);
        session.removeAttribute(Constants.SESSION_SECURITY_CODE);
        session.setTimeout(1000*60*30);
        return Result.success();
    }

}
